import { login, getUserInfo, getUserMyPermissions } from '@/api/user'
// import router from '@/router/index'
import { getToken, setToken, removeToken, setTimer, getTimer, removeTimer } from '@/utils/auth'
// import { resetRouter } from '@/router'

const state = {
  token: getToken(), // token值
  userInfo: {}, // 账户个人信息
  mypermissions: {}, // 账户权限信息
  timer: getTimer() // 拿到时间戳
}

const mutations = { // 状态管理的函数
  setToken: (state, token) => {
    state.token = token
  },
  // 清空token 及 个人信息 及本地存储
  removeToken: (state) => {
    removeToken()
    state.userInfo = {}
    state.mypermissions = {}
    state.token = ''
  },
  setuserInfo(state, data) {
    state.userInfo = data
  },
  setmypermissions(state, data) {
    state.mypermissions = data
  }
}

const actions = {
  // 登录
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res.data.jwt)
    setToken(res.data.jwt)
    // router.push('/')
  },
  // 登出
  async logout(store) {
    store.commit('removeToken')
    store.commit('permission/removeRoute')
    // 退出删除时间戳
    removeTimer()
  },
  // 拿到登入用户的个人信息与权限信息
  async getUserMessage(store) {
    const res = await getUserInfo()
    const res1 = await getUserMyPermissions()
    store.commit('setuserInfo', res.data)
    store.commit('setmypermissions', res1.data)
    // 保存时间戳到本地
    setTimer()
    // return res.data.data + res1.data.data
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

